<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
    <%@ include file="/include/tasklibs.jsp" %>
    <style>
        .fixed-table-body thead th .th-inner {
            text-align: center;
        }

        .shotline {
            border-bottom: solid 2px #B4B4B4;
        }

        .textAlign-right {
            text-align: right;
        }

        #storeInfoTableContainer {
            display: none;
            padding: 10px;
        }

        .btn-default {
            background-color: #2F4050;
        }

        .dz-success-mark {
            display: none;
        }

        .dz-error-mark {
            display: none;
        }

        .dz-error-message {
            display: none;
        }

        .bv-form .help-block {
            margin-bottom: 0;
        }

        .bv-form .tooltip-inner {
            text-align: left;
        }

        .nav-tabs li.bv-tab-success > a {
            color: #3c763d;
        }

        .nav-tabs li.bv-tab-error > a {
            color: #a94442;
        }

        .bv-form .bv-icon-no-label {
            top: 0;
        }

        .bv-form .bv-icon-input-group {
            top: 0;
            z-index: 100;
        }
    </style>

    <script type="text/javascript">
        function fucCheckLength(strTemp) {
            if(null !=strTemp && ""!=strTemp){
                return strTemp.length;
            }else {
                return 0;
            }
            return strTemp.length;
        }
        $(function () {
            $('form').bootstrapValidator({
                feedbackIcons: {
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                },
                excluded:[":disabled"],
                fields: {
                    taskName: {
                        validators: {
                            notEmpty: {
                                message: '任务名称不能为空'
                            },
                            callback: {
                                message: '字数不能超过30',
                                callback: function (value, validator, $field) {
                                    var m=fucCheckLength(value);
                                    return m<31;
                                }
                            }
                        }
                    },
                    startTime: {
                        validators: {
                            notEmpty: {
                                message: '开始时间不能为空'
                            },
                            callback: {
                                message: '开始日期不能大于结束日期',
                                callback: function (value, validator, $field) {
                                    var begin = $('#startDate').val();
                                    var end = $('#endDate').val();
                                    $('#startDate').keypress();
                                    $('#endDate').keypress();
                                    console.log(begin);
                                    console.log(end);
                                    return begin <= end;
                                }
                            }
                        }
                    },
                    endTime: {
                        validators: {
                            notEmpty: {
                                message: '结束时间不能为空'
                            },
                            callback: {
                                message: '结束日期不能小于开始日期',
                                callback: function (value, validator, $field) {
                                    var begin = $('#startDate').val();
                                    var end = $('#endDate').val();
                                    $('#startDate').keypress();
                                    $('#endDate').keypress();
                                    console.log(parseInt(end));
                                    console.log(parseInt(begin))
                                    console.log(begin > end);
                                    return end >= begin;
                                }
                            }
                        }
                    },
                    reward: {
                        validators: {
                            callback: {
                                message: '只能输入数字,且小数点后最多两位！',
                                callback: function (value, validator, $field) {
                                    if(value.length>0 ){
                                        var reg = /^([1-9]\d*|0)(\.\d{1,2})?$/;
                                        return parseFloat(value) > 0 && reg.test(value);
                                    }else {
                                        return true;
                                    }
                                }
                            }
                        }
                    },
                    storeCode: {
                        validators: {
                            notEmpty: {
                                message: '任务地点不能为空'
                            }
                        }
                    },
                    taskGuidancePicture:{
                        validators: {
                            callback: {
                                message: '图片只能上传5个,请删除多余和带X的图片',
                                callback:function(value, validator,$field,options){
                                    var begin = $('#taskDropzone').attr("value");
                                    if($(".dz-error").length>0){
                                        return false;
                                    }
                                    console.log(begin);
                                    if(null ==begin|| ""==begin){
                                        return true;
                                    }else {
                                        return parseInt(begin)<6;
                                    }
                                }
                            }
                        }
                    },
                    taskRequire:{
                        validators: {
                            callback: {
                                message: '字符内容长度不能超过500',
                                callback:function(value, validator,$field,options){
                                    var m=fucCheckLength(value);
                                    console.log(m)
                                    return m<501;
                                }
                            }
                        }
                    },
                    taskGuidanceWords:{
                        validators: {
                            callback: {
                                message: '字符内容长度不能超过500',
                                callback:function(value, validator,$field,options){
                                    var m=fucCheckLength(value);
                                    console.log(m)
                                    return m<501;
                                }
                            }
                        }
                    }
                }
            });
        });

        function changeVal(type) {
            if (type == 1) {
                setTimeout("val(1)", 2000);
            } else {
                setTimeout("val(2)", 2000);
            }
        }

        function val(type) {
            var bootstrapValidator = $("#taskForm").data('bootstrapValidator');
            if (type == 1) {
                bootstrapValidator.updateStatus('endTime', 'NOT_VALIDATED').validateField('endTime');
                bootstrapValidator.updateStatus('startTime', 'NOT_VALIDATED').validateField('startTime');
            } else {
                var storeCode = "";
                $("#childTaskList  tr td:nth-child(3)").each(function (j, el) {
                    console.log($(this).html());
                    if ("" == storeCode) {
                        storeCode = $(this).html()
                    } else {
                        storeCode = $(this).html() + "," + storeCode;
                    }
                });
                console.log(storeCode);
                $("#storeCode").val(storeCode);
                bootstrapValidator.updateStatus('storeCode', 'NOT_VALIDATED').validateField('storeCode');
            }
        }
        function saveReport() {
            var bootstrapValidator = $("#taskForm").data('bootstrapValidator');
            if(!bootstrapValidator.isValid()){
                return false;
            }
            var status = $("#status").val();
            // jquery 表单提交
            $.ajax({ type: "POST",
                url:"web/saveParentTask.json",
                data:$('#taskForm').serialize() , success: function(data){
                    if(data.result==1){
                        bootstrapValidator.updateStatus('storeCode', 'VALID').validateField('storeCode');
                        // $("#taskid").val(data.msg);
                        if(status=='SAVE'){
                            layer.msg("保存成功");
                            return false;
                        }else{
                            layer.msg("发布成功");
                            $('.J_iframe').load('web/taskList.html');
                        }
                    }else{
                        layer.msg(data.msg);
                        return false;
                    }
                }, error: function(data) {
                    layer.msg("操作失败");
                    return false;
                },});
            return false; // 必须返回false，否则表单会自己再做一次提交操作，并且页面跳转
        }
    </script>
</head>
<div class="animated fadeInRight">
    <div class="row">
        <div class="col-sm-12">
            <div class="ibox float-e-margins">
                <div class="ibox-content">
                    <form method="post" class="form-horizontal" action="web/saveParentTask.json" id="taskForm" onsubmit = "return saveReport();">
                        <input type="hidden" name="id" id="id" value="${task.id}">
                        <input type="hidden" id="status" name="status" value="SAVE">
                        <input type="hidden" id="imageUrl" name="taskGuidancePictures"
                               value="${task.taskGuidancePictures}">

                        <div class="form-group">
                            <label class="col-sm-2 control-label">任务类型</label>

                            <div class="col-sm-8">
                                <label class="radio-inline i-checks">
                                    <input type="radio" value="DATA"
                                           <c:if test="${task.taskType=='DATA' }">checked</c:if>
                                           name="taskType">数据采集</label>


                                <label class="radio-inline i-checks">
                                    <input type="radio" value="INVEST"
                                           <c:if test="${task.taskType=='INVEST' }">checked</c:if>
                                           name="taskType">市调</label>


                                <label class="radio-inline i-checks">
                                    <input type="radio" value="ARRANG"
                                           <c:if test="${task.taskType=='ARRANG' }">checked</c:if>
                                           name="taskType">理贷</label>


                                <label class="radio-inline i-checks">
                                    <input type="radio" value="PROMOTION"
                                           <c:if test="${task.taskType=='PROMOTION' }">checked</c:if> name="taskType">促销</label>

                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">任务名称</label>

                            <div class="col-sm-8">
                                <input type="text" placeholder="请输入任务名称" id="taskName" name="taskName"
                                       value="${task.taskName}" class="form-control" id="taskNameInput" required="true">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">任务周期</label>

                            <div class="col-sm-8">
                                <input id="startDate" class="laydate-icon form-control layer-date" name="startTime"
                                       value="${task.startTime}" onblur="changeVal(1)" autocomplete="off">
                                <span class="shotline">&emsp;&emsp;&emsp;</span>
                                <input id="endDate" class="laydate-icon form-control layer-date" name="endTime"
                                       value="${task.endTime}" onblur="changeVal(1)" autocomplete="off">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">任务赏金</label>

                            <div class="col-sm-4">
                                <div class="input-group m-b"><span class="input-group-addon">&yen;</span>
                                    <input type="text" placeholder="" class="form-control" name="reward"
                                           value="${task.reward}">
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">任务地点</label>

                            <div class="col-sm-4">
                                <button class="btn btn-default" type="button" id="addAddressBtn" onblur="changeVal(2)">
                                    <i class="fa fa-plus"></i>&nbsp;&nbsp;添加地点
                                </button>
                                <button class="btn btn-default " type="button" id="excelDropzone" onblur="changeVal(2)"
                                        onmousedown="changeData()">
                                    <i class="fa fa-upload"></i>&nbsp;&nbsp;导入Excel
                                    <input style="height:0.05px;width:0px;padding:0px;margin:0px;" id="storeCode"
                                           name="storeCode">
                                </button>
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="col-sm-2 control-label">任务要求</label>

                            <div class="col-sm-8">
                                <textarea id="requireEditor" placeholder="请输入任务要求" name="taskRequire">
                                    ${task.taskRequire}
                                </textarea>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">任务指引</label>

                            <div class="col-sm-8">
                                <textarea id="guideEditor" placeholder="请输入任务指引" name="taskGuidanceWords">
                                    ${task.taskGuidanceWords}
                                </textarea>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">附件照片上传</label>

                            <div class="col-sm-8">
                                <div id="fileDrop" style="min-height: 250px;" class="dropzoneContainer dropzone "
                                     name="taskGuidancePicture"></div>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-sm-3 col-sm-offset-5">
                                <button class="btn btn-default" type="submit" id="publisParentTaskBtn"
                                        onmousedown="changeStatus(1)">发布
                                </button>
                            </div>
                            <div class="col-sm-4">
                                <button class="btn btn-default" type="submit" id="submitParentTaskBtn"
                                        onmousedown="changeStatus(0)">保存
                                </button>
                                <input class="btn btn-default" style="width:70px"   value="取消" onclick="return changeType();"
                                       class="Button">
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <div class="col-sm-12">
            <div class="ibox float-e-margins">
                <div id="toolbar">
                    <button id="buttonRemove" class="btn btn-default">删除子任务</button>
                </div>
                <div class="ibox-content">
                    <table id="childTaskList"></table>
                </div>
            </div>
        </div>
    </div>
    <!--选择门店信息表格-->
    <div id="storeInfoTableContainer">
        <table id="storeInfoTable"></table>
    </div>
</div>

<script>

    var sourceUrl = '${task.taskGuidancePictures}';
    function changeType(){
        var id = $("#id").val();
        $('.J_iframe').load('web/mainTaskManage.html?id='+id);
    }

    var taskName = "";
    var startDate = "";
    var endDate = "";
    var $table = $('#childTaskList');
    var $button = $('#buttonRemove');
    $(function () {
        var bootstrapValidator = $("#taskForm").data('bootstrapValidator');
        $button.click(function () {
            var ids = $.map($table.bootstrapTable('getSelections'), function (row) {
                return row.id;
            });
            $table.bootstrapTable('remove', {
                field: 'id',
                values: ids
            });
            var storeCode = "";
            $("#childTaskList  tr td:nth-child(4)").each(function (j, el) {
                if ("" == storeCode) {
                    storeCode = $(this).html()
                } else {
                    storeCode = $(this).html() + "," + storeCode;
                }
            });
            $("#storeCode").val(storeCode);
            var bootstrapValidator = $("#taskForm").data('bootstrapValidator');
            bootstrapValidator.updateStatus('storeCode', 'NOT_VALIDATED').validateField('storeCode');
            $("#childTaskList").bootstrapTable('refreshOptions', {
                sidePagination: 'client'  //改为客户端分页
            });
        });

    });
    function removeFile(fileName){
        var source = $("#imageUrl").val();
        var strs= new Array();
        var result= new Array();
        strs=source.split(",");
        var imageUrl = null;
        for (i=0;i<strs.length ;i++ )
        {
            if(strs[i].indexOf(fileName)>0){
                console.log("删除他")
            }else {
                if (imageUrl != null && imageUrl != "") {
                    imageUrl = imageUrl + "," +strs[i]
                } else {
                    imageUrl = strs[i];
                }
            }
        }
        $("#imageUrl").val(imageUrl);
        $(this).remove();

    }
    function changeData() {
        taskName = $("#taskNameInput").val();
        startDate = $("#startDate").val();
        endDate = $("#endDate").val();
    }
    function changeStatus(val) {
        if (val == 0) {
            $("#status").val("SAVE");
        } else {
            $("#status").val("PUBLISH");
        }

        var storeCode = "";
        $("#childTaskList  tr td:nth-child(4)").each(function (j, el) {
            if ("" == storeCode) {
                storeCode = $(this).html()
            } else {
                storeCode = $(this).html() + "," + storeCode;
            }
        });
        $("#storeCode").val(storeCode);
    }
    var Controller = {
        taskListTable: null,
        storeInfoTable: null,
        init: function () {
            Controller.initLaydate();
            Controller.initEditor();
            Controller.initDropzone();
            Controller.initTable();
        },
        initLaydate: function () {
            laydate({
                elem: '#startDate',
                event: 'focus'
            });
            laydate({
                elem: '#endDate',
                event: 'focus'
            });
        },
        initDropzone: function () {
            Dropzone.autoDiscover = false;
            $("#excelDropzone").dropzone({ url: "web/taskExcelUpload.json", acceptedFiles: ".xls,.xlsx", addRemoveLinks: true,
                init: function () {
                    this.on("success", function (files, response) {
                        if (response.result) {
                            console.log(response.rows);
                            var json = response.rows;

                            $(json).each(function (i, ele) {
                                var next = 0;
                                $("#childTaskList  tr td:nth-child(4)").each(function (j, el) {
                                    if (ele.storeCode == $(this).html()) {
                                        next = 1;
                                        return false;
                                    }
                                });
                                if (next == 1) {
                                    return true;
                                }
                                Controller.taskListTable.bootstrapTable('insertRow', {
                                    index: Controller.taskListTable.bootstrapTable('getData').length + 1,
                                    row: {
                                        id: Controller.taskListTable.bootstrapTable('getData').length + 1,
                                        storeCode: ele.storeCode,
                                        taskName: $('#taskNameInput').val(),
                                        storeName: ele.storeName,
                                        storeAddress: ele.storeAddress,
                                        startDate: $('#startDate').val(),
                                        endDate: $('#endDate').val()
                                    }
                                });
                            });
                            if(null != response.msg && "" !=response.msg) {
                                layer.alert(response.msg);
                            }
                        }
                    });
                } });

            $("#fileDrop").dropzone({ url: "web/taskImageUpload.json", acceptedFiles: "image/*", addRemoveLinks: true, maxFiles: 5,
                init: function () {
                    this.emit("initimage", sourceUrl);
                    this.on("success", function (files, response) {
                        var imageUrl = $("#imageUrl").val();
                        if (imageUrl != null && imageUrl != "") {
                            imageUrl = imageUrl + "," + response.msg
                        } else {
                            imageUrl = response.msg;
                        }
                        $("#imageUrl").val(imageUrl);
                        var bvbootstrapValidator = $("#taskForm").data('bootstrapValidator');
                        if($("div").hasClass("dz-error")){
                            $("#taskDropzone").attr("value","6");
                            bvbootstrapValidator.updateStatus('taskGuidancePicture', 'INVALID').validateField('taskGuidancePicture');
                        }else{
                            bvbootstrapValidator.updateStatus('taskGuidancePicture', 'NOT_VALIDATED').validateField('taskGuidancePicture');
                        }
                    });
                    this.on("removedfile", function (file) {
                        var bvbootstrapValidator = $("#taskForm").data('bootstrapValidator');
                        if($("div").hasClass("dz-error")){
                            $("#taskDropzone").attr("value","6").change();
                            bvbootstrapValidator.updateStatus('taskGuidancePicture', 'INVALID').validateField('taskGuidancePicture');
                        }else{
                            $("#taskDropzone").attr("value","0");
                            bvbootstrapValidator.updateStatus('taskGuidancePicture', 'NOT_VALIDATED').validateField('taskGuidancePicture');
                        }
                        if($(".dz-preview").length<6){//判断图片数量
                            bvbootstrapValidator.updateStatus('taskGuidancePicture', 'NOT_VALIDATED').validateField('taskGuidancePicture');
                        }
                            removeFile(file.name);
                    });
                    this.on("maxfilesreached", function (file) {
                        var bvbootstrapValidator = $("#taskForm").data('bootstrapValidator');

                        bvbootstrapValidator.updateStatus('taskGuidancePicture', 'INVALID').validateField('taskGuidancePicture');
                    });
                } });
        },
        initTable: function () {
            Controller.taskListTable = $('#childTaskList').bootstrapTable({
                url: 'web/findChildTaskList.json?parentTaskId=' + '${task.id}',
                columns: [
                    {
                        field: 'id',
                        title: '序号',
                        width: '40px',
                        checkbox: true
                    },
                    {
                        field: 'code',
                        title: '任务编码',
                        width: '40px'
                    },
                    {
                        field: 'taskName',
                        title: '任务名称'
                    },
                    {
                        field: 'storeCode',
                        title: '门店编码'
                    },
                    {
                        field: 'storeName',
                        title: '门店名称'
                    },
                    {
                        field: 'storeAddress',
                        title: '门店地址'
                    },
                    {
                        field: 'startDate',
                        title: '开始日期'
                    },
                    {
                        field: 'endDate',
                        title: '结束日期'
                    }
                ],
                pagination: true,
                pageSize: 1000,
                sidePagination: "server",
                idField: 'id', //主键
                uniqueId: 'id'

            });

            Controller.storeInfoTable = $('#storeInfoTable').bootstrapTable({
                url: 'web/getAllStore.json',
                columns: [
                    {
                        checkbox: true,
                        field: 'checkbox'
                    },
                    {
                        field: 'storeCode',
                        title: '门店编码'
                    },
                    {
                        field: 'storeName',
                        title: '门店名称'
                    },
                    {
                        field: 'storeAddress',
                        title: '门店地址'
                    }
                ],
                search: true,
                checkboxHeader: true,
                sidePagination: 'client',
            });
        },
        initEditor: function () {
            var bootstrapValidator = $("#taskForm").data('bootstrapValidator');
            var requireEditor = new Simditor({
                textarea: $('#requireEditor')
            });
            requireEditor.on("blur",(function(){
                bootstrapValidator.updateStatus('taskRequire', 'NOT_VALIDATED').validateField('taskRequire');
            }))
            var guideEditor = new Simditor({
                textarea: $('#guideEditor')
            });
            guideEditor.on("blur",(function(){
                bootstrapValidator.updateStatus('taskGuidanceWords', 'NOT_VALIDATED').validateField('taskGuidanceWords');
            }))
        },
        bindEvents: function () {
            $('#addAddressBtn').click(function () {
                $('#storeInfoTable').bootstrapTable("resetSearch");
                // 弹出框
                layer.open({
                    type: 1,
                    title: '选择门店',
                    content: $('#storeInfoTableContainer'), // 只要是DOM就会出现CSS显示错误？？？？
                    area: ['800px', '500px'],
                    zIndex: 10,
                    shade: false,
                    btn: ['确认添加'],
                    btn1: function () {
                        // 勾选的门店信息添加到最下面的表格中
                        var checkedData = Controller.storeInfoTable.bootstrapTable('getSelections');
                        if (checkedData.length > 0) {

                            $(checkedData).each(function (i, ele) {
                                var next = 0;
                                $("#childTaskList  tr td:nth-child(4)").each(function (j, el) {
                                    if (ele.storeCode == $(this).html()) {
                                        next = 1;
                                        return false;
                                    }
                                });
                                if (next == 1) {
                                    return true;
                                }
                                Controller.taskListTable.bootstrapTable('insertRow', {
                                    index: Controller.taskListTable.bootstrapTable('getData').length + 1,
                                    row: {
                                        id: Controller.taskListTable.bootstrapTable('getData').length + 1,
                                        storeCode: ele.storeCode,
                                        taskName: $('#taskNameInput').val(),
                                        storeName: ele.storeName,
                                        storeAddress: ele.storeAddress,
                                        startDate: $('#startDate').val(),
                                        endDate: $('#endDate').val()
                                    }
                                });
                            });
                        }
                        $("#childTaskList").bootstrapTable('refreshOptions', {
                            sidePagination: 'client'  //改为客户端分页
                        })
                    }

                });
            });
        }
    }

    $(document).ready(function () {
        $('.i-checks').iCheck({
            checkboxClass: 'icheckbox_square-green',
            radioClass: 'iradio_square-green',
        });
        Controller.init();
        Controller.bindEvents();
        $(".dz-size").empty();
    });

</script>